package com.lagou.config;

import com.lagou.pojo.Configuration;
import com.lagou.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

public class XMLMapperBuilder {

    private Configuration configuration;

    public XMLMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public void parse(InputStream inputStream) throws DocumentException {

        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();

        String namespace = rootElement.attributeValue("namespace");

        // 将select、insert、update、delete类型sql找出来放入map
        for (SqlType value : SqlType.values()) {
            List<Element> list = rootElement.selectNodes("//" + value.value);
            for (Element element : list) {
                String id = element.attributeValue("id");
                String resultType = element.attributeValue("resultType");
                String parameterType = element.attributeValue("parameterType");
                String sqlText = element.getTextTrim();
                MappedStatement mappedStatement = new MappedStatement();
                mappedStatement.setId(id);
                mappedStatement.setResultType(resultType);
                mappedStatement.setParameterType(parameterType);
                mappedStatement.setSql(sqlText);
                mappedStatement.setSqlType(value.value);
                String key = namespace + "." + id;
                configuration.getMappedStatementMap().put(key, mappedStatement);
            }
        }
    }


    public enum SqlType {
        SELECT("select", "查询"),  INSERT("insert", "新增"), UPDATE("update", "修改"), DELETE("delete", "删除");

        private String value;
        private String text;

        SqlType(String value, String text) {
            this.value = value;
            this.text = text;
        }

        public String getValue() {
            return value;
        }

        public String getText() {
            return text;
        }
    }

}
